<template>
    <div class="app-container">
      <div class="filter-container">
        <el-input type="input" v-model="listQuery.pic_id" placeholder="图片id搜索" style="width: 220px;"></el-input>
        <el-select v-model="listQuery.classify_id" filterable placeholder="请选择分类">
            <el-option
            v-for="(v, key) in classify"
            :key="key"
            :label="v"
            :value="key"
            >
            </el-option>
        </el-select>

        <el-select v-model="listQuery.author_id" filterable placeholder="请选择作者">
            <el-option
            v-for="(v, key) in author_list"
            :key="key"
            :label="v"
            :value="key"
            >
            </el-option>
        </el-select>

        <el-select v-model="listQuery.status" placeholder="请选择状态">
            <el-option label="正常" value="1" > </el-option>
            <el-option label="禁用" value="0" > </el-option>
        </el-select>

        <a-button type="primary" size="large" @click="handleFilter">
          搜索
        </a-button>
        <a-button type="default" size="large" @click="handleCancel">
          重置
        </a-button>
        <br/><br/>
        <el-button
        plain size="small"
            v-waves
            class="filter-item btn"
            type="success"
            @click="showAdd()"
        >添加图片</el-button>
      </div>
  
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          key="2"
          label="图片"
          align="center"
          prop=""
          min-width="50"
        >
        <template slot-scope="{row}">
          <!-- {{ is_video(row.img_path.img_thumbnail) }} -->
          <el-link v-if="is_video(row.img_path.img_thumbnail)" @click="show_video(row.img_path.img_thumbnail)" type="success">查看视频</el-link>
          <el-image v-else
              style="width: 100px; height: 100px"
              :src="row.img_path.img_thumbnail ? row.img_path.img_thumbnail: '1'" 
              :preview-src-list="[row.img_path.img_thumbnail]">
          </el-image>
            
        </template>
        </el-table-column>
        <el-table-column
          key="1"
          label="作者"
          align="center"
          prop="author_id"
          min-width="50"
        >
        <template slot-scope="{row}">
            <span>{{ author_list[row.author_id] }}</span>
        </template>
        </el-table-column>
        
        <el-table-column
          key="3"
          label="图片id"
          align="center"
          prop="pic_id"
          min-width="50"
        >
        </el-table-column>
        <el-table-column
          key="5"
          label="类别"
          align="center"
          prop="classify_id"
          min-width="50"
        >
            <template slot-scope="{row}">
                <span>{{ classify[row.classify_id] }}</span>
            </template>
        </el-table-column>

        <el-table-column
          key="6"
          label="下载次数"
          align="center"
          prop="download_sum"
          min-width="50"
        >
        <template slot-scope="{row}">
            <span>{{ row.download_sum}}</span>
        </template>
        </el-table-column>

        <el-table-column
          key="7"
          label="状态"
          align="center"
          prop="status"
          min-width="50"
        >
        <template slot-scope="{row}">
            <span>{{ row.status == '1'? '正常': '禁用' }}</span>
        </template>
        </el-table-column>
  
        <el-table-column
          key="4"
          label="操作"
          align="center"
          prop="123"
          min-width="50"
        >
        <template slot-scope="{row}">
            <el-link v-if="row.status == '1'" type="danger" @click="updateImg1(row, 0)">禁用</el-link>
    
            <el-link v-if="row.status == '0'" type="primary" @click="updateImg1(row, 1)">启用</el-link>
        </template>
        
        </el-table-column>
  
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        class="pageShow"
        :page.sync="listQuery.page"
        :page_size.sync="listQuery.page_size"
        @pagination="getList"
      />
  
  
       <div>
        <el-dialog
            :title="'添加图片'"
            :visible.sync="bookFormShow"
            width="50%"
            :before-close="handleClose"
            class="fullwidth"
            enctype="multipart/form-data"
            >
            <div>
                <el-form :model="temp" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                    <el-form-item label="分类" prop="classify_id">
                        <el-select v-model="temp.classify_id" filterable placeholder="请选择">
                          <el-option
                          v-for="(v, key) in classify"
                          :key="key"
                          :label="v"
                          :value="key"
                          >
                          </el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="作者" prop="author_id">
                        <el-select v-model="temp.author_id" filterable placeholder="请选择">
                          <el-option
                          v-for="(v, key) in author_list"
                          :key="key"
                          :label="v"
                          :value="key"
                          >
                          </el-option>
                      </el-select>
                    </el-form-item>
  
                    <el-form-item label="图片" prop="img">
                      <!-- http://api_data.ydwhgs.com/api/tupian/upload/img -->
                        <el-upload
                            class="upload-demo"
                            action="http://up-cn-east-2.qiniup.com"
                            :data="postdata"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="handleAvatarSuccess"
                            :file-list="fileList"
                            :multiple="true"
                            :limit="50"
                            :before-upload = "before_upload"
                            :on-exceed="handleExceed"
                            accept=".jpg,.png,.gif,.jpeg,.mp4,.MOV"
                            list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif/mp4/MOV文件，单个文件不超过20M,每次只能上传50张</div>
                        </el-upload>
                    </el-form-item>
<!-- 
                    <el-form-item label="状态">
                        <el-radio-group v-model="temp.status">
                        <el-radio label="1">正常</el-radio>
                        <el-radio label="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item> -->
  
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="bookFormShow = false">取 消</el-button>
                <el-button type="primary" @click="temp.is_edit ? editBook1(): addBook1()">提 交</el-button>
            </span>
            </el-dialog>
            <VideoPlayer :url="video_url" :show="video_show" @clear="video_url = '', video_show=false"></VideoPlayer>
        </div>
    </div>
  </template>
  
  <script>
  import {
    getPhotoCatygory,
    getAuthor,
    uploadImg,
    updateImg,
    getPhoto,
    getQiniuToken
  } from "@/api/admin/book";
  import waves from "@/directive/waves"; // waves directive
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import { MessageBox, Message } from "element-ui";
  import {is_video, get_key} from '@/utils/index'
  import VideoPlayer from "@/components/VideoPlayer"
  export default {
    name: "Report",
    components: { Pagination, VideoPlayer},
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
    },
    data() {
      return {
        postdata:{
            token: '',
            key: '',
            bucket: 'dy-pic'
        },
        is_video,
        video_url: '',
        video_show: false,
        userType: this.$store.state.user.type,
        username: this.$store.state.user.name.username,
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: false,
        listQuery: {
          page: 1,
          page_size: 20,
          author_id: "",
          classify_id: "",
          status: "",
          pic_id: ''
        },
        imageUrl: '',
        temp:{
            is_edit:false,
            classify_id: '',
            author_id: '',
            img: '',
            img_list: []
        },
        bookFormShow: false,
        rules: {
            author_id: [
            { required: true, message: '请输入口令', trigger: 'blur' }
          ],
          classify_id: [
            { required: true, message: '请输入作者昵称', trigger: 'blur' }
          ],
          img: [
            { required: true, message: '请上传封面', trigger: 'blur' }
          ]
        },
        classify:{},
        author_list: {},
        fileList: []
      };
    },
    created() {
    },
    mounted() {
      this.getToken()
        this.getAuthor()
        this.getClassify()
        this.getList()
    },
    methods: {
      getToken(){
        getQiniuToken().then(res =>{
          if(res.code == 200){
            this.postdata.token = res.data.uptoken
          }else{
            Message({
              message: '获取token失败，请刷新页面',
              type: "error",
              duration: 2000,
            })
          }
          console.log(this.postdata)
        })
      },
      show_video(url){
        this.video_show = true
        this.video_url = url
      },
       getAuthor(){
          getAuthor({menu: '1'}).then(res => {
                if(res.code == 200){
                  this.author_list = res.data.list
                    // for (let v of res.data.author_list){
                    //     this.author_list[v.author_id] = v.nick_name
                    // }
                }
            })
        },
      getClassify(){
        getPhotoCatygory().then(res => {
            if(res.code == 200){
                this.classify = res.data.category;
            }
        })
      },
      classifyName(classify_id){
        for(let item of this.classify){
            if (classify_id == item.category_id){
                return item.name
            }
        }
  
      },
      getList() {
        this.listLoading = true;
        getPhoto(this.listQuery).then(res => {
          this.listLoading = false;
  
          if (res.code == 200){
            this.list = res.data.pic_list
            this.total = res.data.total
          }else{
            Message({
                message: res.message,
                type: "error",
                duration: 2000,
              });
          }
        })
            
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      handleCancel() {
        this.listQuery.page = 1;
        this.listQuery.classify_id = '';
        this.listQuery.author_id = ''
        this.listQuery.status = ''
        this.listQuery.pic_id = ''
        this.getList();
      },
      detail(row){
        this.$router.push({
            path: '/book/detail',
            query: row
        })
      },
      handleClose(){
        this.bookFormShow = false
      },
      showAdd(){
        this.temp = {
            is_edit:false,
            classify_id: '',
            author_id: '',
            img: []
        }
        this.fileList = []
        this.temp.img_list = []
        this.bookFormShow = true
      },
      updateImg1(row, status){
        updateImg({pic_id: row.pic_id, status: status}).then(res => {
            if (res.code == 200){
                    Message({
                        message: res.message,
                        type: "success",
                        duration: 2000,
                    })
                    this.getList()
                }else{
                    Message({
                        message: res.message,
                        type: "error",
                        duration: 2000,
                    })
                }
        })
      },
      addBook1(){
        this.temp.img = JSON.stringify(this.temp.img_list)
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            
            uploadImg(this.temp).then(res => {
                if (res.code == 200){
                    this.bookFormShow = false
                    Message({
                        message: res.message,
                        type: "success",
                        duration: 2000,
                    })
                    this.temp.img_list = []
                    this.getList()
                }else{
                    Message({
                        message: res.message,
                        type: "error",
                        duration: 2000,
                    })
                }
            })
          } else {
          }
        });
      },
      before_upload(file){
        // console.log('before_upload', file)
        this.postdata.key = 'avatar/' + get_key(file.name)
        // console.log(this.postdata)
      },
      handleAvatarSuccess(res, file, fileList){
        // console.log('handleAvatarSuccess', res, file, fileList)
        this.temp.img_list.push(res.key)
        // if(res.code == 200){
        //   this.temp.img_list.push(res.data.img_path)
        // }else{
        //   let index = this.temp.img_list.indexOf(file.response.data.img_path)
        //   this.temp.img_list.splice(index, 1)
        //   for(let index = 0; index < fileList.length; index++){
        //       if(fileList[index].name == res.data.file_name){
        //         fileList[index].name = fileList[index].name + '     ' + res.message;
        //         fileList[index].status = 'error'
        //       }
        //     }
        //   Message({
        //         message: res.message,
        //         type: "error",
        //         duration: 2000,
        //     })
        // }
      },
      handleRemove(file, fileList) {
        // console.log('handleRemove',file, fileList);
        let index = this.temp.img_list.indexOf(file.response.data.img_path)
        this.temp.img_list.splice(index, 1)
        // console.log(this.temp.img)
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        Message({
                message: `当前限制选择 50 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
                type: "error",
                duration: 2000,
            })
        // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
    }
  };
  </script>
  
  <style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 95%;
  }
  .pageHidden {
    display: none;
  }
  @media (max-width: 550px) {
    .pageShow {
      display: none;
    }
    .pageHidden {
      display: block;
    }
    .pickertime {
      width: 100%;
    }
  }
  .filter-item {
    margin-bottom: 3px;
  }
  @media (max-width: 550px) {
  .pageShow {
    display: none;
  }
  .pageHidden {
    display: block;
  }
  .fullwidth {
    width: 100%;
    margin-left: 0;
  }
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .w-100{
  width: 100px;
  }
  </style>
  